package com.shy.base.util;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;

/**
 * 处理web/property Date时间格式
 * 
 * @author shy
 * @date 2016-8-23
 */
public class CustomDateEditor extends PropertyEditorSupport {

    private final DateFormat dateFormat10 = new SimpleDateFormat("yyyy-MM-dd");
    private final DateFormat dateFormat13 = new SimpleDateFormat("yyyy-MM-dd HH");
    private final DateFormat dateFormat16 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private final DateFormat dateFormat19 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * Parse the Date from the given text, using the specified DateFormat.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || !StringUtils.hasText(text)) {
            setValue(null);
        } else {
            try {
                text = text.trim();
                int length = text.length();
                DateFormat format = null;
                switch (length) {
                    case 10:
                        format = dateFormat10;
                        break;
                    case 13:
                        format = dateFormat13;
                        break;
                    case 16:
                        format = dateFormat16;
                        break;
                    case 19:
                        format = dateFormat19;
                        break;
                    default:
                        format = dateFormat10;
                        break;
                }
                if (format != null) {
                    setValue(format.parse(text));
                } else {
                    throw new IllegalArgumentException("Could not parse date:" + text);
                }
            } catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? this.dateFormat10.format(value) : "");
    }
}
